package com.mimo.logic.room.service.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.mimo.common.cache.ICache;
import com.mimo.common.listener.IMessage;
import com.mimo.common.room.event.RoomTopicEvent;
import com.mimo.common.utils.JsonUtils;

@Component
public class RoomCacheListener implements IMessage {

  @Resource(name = "roomCache")
  private ICache<String, String[], String> roomCache;

  @Value("${logic.room.channel}")
  private String channel;

  @Override
  public void onMessage(String event) {
    RoomTopicEvent evt = JsonUtils.parseJson(event, RoomTopicEvent.class);
    switch (evt.getType()) {
      case Created:
        roomCache.create(evt.getRoomId());
        break;
      case Destoried:
        roomCache.clear(evt.getRoomId());
        break;
      case MemberJoint:
        roomCache.add(evt.getRoomId(), evt.getMember());
        break;
      case MemberLeft:
        roomCache.remove(evt.getRoomId(), evt.getMember());
        break;
      default:
        throw new UnsupportedOperationException();
    }
  }

  @Override
  public String getTopic() {
    return channel;
  }

}
